package org.summerframework.component.security.spring.filter;

import org.summerframework.component.security.LoginData;
import org.summerframework.component.security.context.RequestContextFactory;
import org.summerframework.component.security.core.service.LoginManage;
import org.summerframework.component.security.spring.LoginSecurityData;
import org.summerframework.component.security.spring.SecurityRoleService;
import org.summerframework.core.util.ViewUtil;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Getter
@Setter
public class LoginFilter extends UsernamePasswordAuthenticationFilter {
    private LoginManage loginManage;

    private SecurityRoleService securityRoleService;

    public LoginFilter() {
        super();
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        ModelAndView login = loginManage.login(RequestContextFactory.getCurrentContext());

        LoginData<Object> loginData = RequestContextFactory.getLoginData();
        LoginSecurityData loginSecurityData = null;

        if (loginData.isLogin()) {
            loginSecurityData = new LoginSecurityData(loginData, securityRoleService.getRole(loginData.getUserId()));
            SecurityContextHolder.getContext().setAuthentication(loginSecurityData);
        }

        ViewUtil.render(login, request, response);
        return loginSecurityData;
    }
}
